﻿import kliment.utils.RandomList;
/**
 * ...
 * @author	Kliment
 * @version	1.0.2
 */
class kliment.utils.RandomRun {
	private var _randomList:RandomList;
	private var _isRaned:Array;
	private var _elements:Array;
	private var _interval:Number;
	private var _interval_id:Number;
	
	public function RandomRun(objects:Object, interval:Number, autostart:Boolean) {
		_interval = interval;
		_elements = new Array();
		_isRaned = new Array();
		for (var i in objects) {
			var item = objects[i];
			if (item instanceof MovieClip) {
				_elements.push(item);
				item.stop();	
			}
		}
		_randomList = new RandomList(0, _elements.length - 1);
		if (autostart)
			run();
	}
	
	public function run():Void {
		_next();
	}
	
	private function _next():Void {
		clearInterval(_interval_id);
		var item_mc = _elements[_randomList.nextIndex];
		item_mc.play();
		_isRaned.push(item_mc);
		if (_randomList.remain > 0)
			_interval_id = setInterval(this, '_next', _interval);
	}
	
	public function play():Void {
		var i:Number = _isRaned.length;
		while (i--) {
			_isRaned[i].play();
		}
		_next();
	}
	
	public function stop():Void {
		clearInterval(_interval_id);
		var i:Number = _isRaned.length;
		while (i--) {
			_isRaned[i].stop();
		}
	}
}